import 'dart:convert';
import 'dart:typed_data';
import 'package:encrypt/encrypt.dart';

/// 完整的测试流程，验证修复后的功能
void main() {
  testCompleteFlow();
}

void testCompleteFlow() {
  print('=== 测试完整的加密解密流程 ===');
  
  // 测试数据
  const String testJson = '{"from":"3","uid":null,"utoken":null,"appid":"1004"}';
  const String key = 'test_key_123456789012345678901234';
  const String iv = 'test_iv_123456789012345678901234';
  
  try {
    // 1. 加密数据
    print('1. 加密测试数据:');
    print('原始JSON: $testJson');
    
    final keyObj = Key(Uint8List.fromList(utf8.encode(key).take(32).toList()));
    final ivObj = IV(Uint8List.fromList(utf8.encode(iv).take(16).toList()));
    final encrypter = Encrypter(AES(keyObj, mode: AESMode.cbc));
    final encrypted = encrypter.encrypt(testJson, iv: ivObj);
    final encryptedBase64 = encrypted.base64;
    
    print('加密后Base64: $encryptedBase64');
    
    // 2. 测试Base64验证
    print('\n2. 测试Base64验证:');
    try {
      base64.decode(encryptedBase64);
      print('✅ Base64验证通过');
    } catch (e) {
      print('❌ Base64验证失败: $e');
      return;
    }
    
    // 3. 测试转义字符处理
    print('\n3. 测试转义字符处理:');
    final cleanData = encryptedBase64.replaceAll('\\/', '/');
    print('清理后数据: $cleanData');
    
    if (cleanData == encryptedBase64) {
      print('✅ 转义字符处理正确（无需处理）');
    } else {
      print('⚠️  转义字符被处理');
    }
    
    // 4. 测试解密
    print('\n4. 测试解密:');
    final decrypter = Encrypter(AES(keyObj, mode: AESMode.cbc));
    final encryptedObj = Encrypted(base64.decode(cleanData));
    final decrypted = decrypter.decrypt(encryptedObj, iv: ivObj);
    
    print('解密结果: $decrypted');
    
    // 5. 验证结果
    print('\n5. 验证结果:');
    if (decrypted == testJson) {
      print('✅ 解密成功，数据匹配');
    } else {
      print('❌ 解密失败，数据不匹配');
      print('期望: $testJson');
      print('实际: $decrypted');
    }
    
    // 6. 测试JSON解析
    print('\n6. 测试JSON解析:');
    try {
      final jsonData = jsonDecode(decrypted);
      print('JSON解析成功: $jsonData');
      print('✅ 完整流程测试成功！');
    } catch (e) {
      print('❌ JSON解析失败: $e');
    }
    
  } catch (e) {
    print('❌ 测试失败: $e');
  }
}
